package com.sjsu.cloudmanager.server.service;

import com.sjsu.cloudmanager.dao.CloudUserDao;
import com.sjsu.cloudmanager.model.CloudUser;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: ckempaiah
 * Date: 10/20/11
 * Time: 9:27 AM
 * To change this template use File | Settings | File Templates.
 */
public class CloudUserAuthenticationServiceImpl implements UserDetailsService {

    private CloudUserDao cloudUserDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        CloudUser cloudUser = cloudUserDao.getCloudUser(username);
        List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
        User user = null;
        if (cloudUser != null) {
            GrantedAuthority grantedAuthority = null;
            if (cloudUser.getAdministrator() != null && cloudUser.getAdministrator().equals(true)){
                grantedAuthority = new GrantedAuthorityImpl("ROLE_ADMIN");
            } else {
                grantedAuthority = new GrantedAuthorityImpl("ROLE_ADMIN");
            }
            grantedAuthorities.add(grantedAuthority);
            user = new User(cloudUser.getUserName(), cloudUser.getUserPassword()
                    ,true, true, true, true, grantedAuthorities);
        } else {
            throw new UsernameNotFoundException("User Name not found :"+ username);
        }
        return user;
    }
    //injected bean methods
    public CloudUserDao getCloudUserDao() {
        return cloudUserDao;
    }

    public void setCloudUserDao(CloudUserDao cloudUserDao) {
        this.cloudUserDao = cloudUserDao;
    }
}
